package config

import (
	"fmt"

	"github.com/zeromicro/go-queue/kq"
	configurator "github.com/zeromicro/go-zero/core/configcenter"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest"
)

type Config struct {
	rest.RestConf
	MysqlConfig    MysqlConfig     `json:"MysqlConfig"`
	Auth           JwtAuth         `json:"JwtAuth"`
	RedisConfig    redis.RedisConf `json:"RedisConfig"`
	KqPusherConf   kq.KqConf       `json:"KqPusherConf"`
	KqConsumerConf kq.KqConf       `json:"KqConsumerConf"`
}

type JwtAuth struct {
	AccessSecret string `json:"AccessSecret"`
	AccessExpire int64  `json:"AccessExpire"`
}

type MysqlConfig struct {
	DataSource string `json:"DataSource"`
}

func PullConfig() Config {
	// 创建 subscriber
	ss := NewConsulSubscriber("http://127.0.0.1:8500", "user-config/test/user-api")
	ss.(*ConsulSubscriber).Watch() // 启动 Watch
	// 创建 configurator
	cc := configurator.MustNewConfigCenter[Config](configurator.Config{
		Type: "yaml", // 配置值类型：json,yaml,toml
	}, ss)

	// 获取配置
	// 注意: 配置如果发生变更，调用的结果永远获取到最新的配置
	v, err := cc.GetConfig()
	if err != nil {
		panic(err)
	}
	fmt.Println(v.Name)

	// 如果想监听配置变化，可以添加 listener
	cc.AddListener(func() {
		v, err := cc.GetConfig()
		if err != nil {
			panic(err)
		}
		fmt.Println(v.Name)
	})

	return v
}
